#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>

int  main(int argc, char * argv[])
{
	char *host;
	int sockfd;
	struct sockaddr_in addr;
	struct hostent *hostinfo;
	struct servent *servinfo;
	char buffer[128];
	int len,result;

	if (argc == 1) {
		host = "localhost";
	}else {
		host = argv[1];
	}

	hostinfo = gethostbyname(host);
	if (!hostinfo) {
		fprintf(stderr,"no host:%s\n", host);
		exit(1);
	}

	servinfo = getservbyname("daytime", "tcp");
	if (!servinfo) {
		fprintf(stderr,"no daytime service\n");
		exit(1);
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建一个socket用来通信

	addr.sin_family = AF_INET;
	addr.sin_port = servinfo -> s_port;
	addr.sin_addr = *(struct in_addr*)*hostinfo -> h_addr_list;
	len = sizeof(addr);

	result = connect(sockfd, (struct sockaddr *)&addr,len);//通过套接字描述符和套接字结构体请求连接
	if (result == -1) {
		perror("connect");
		exit(1);
	}

	result = read(sockfd, buffer, sizeof(buffer));
	buffer[result] = '\0';
	printf("read %d bytes: %s", result, buffer);

	close(sockfd);
	exit(0);



}
